package cn.gdut.chengcai.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

import cn.gdut.chengcai.base.ConstantUtil;
import cn.gdut.chengcai.base.RequestUtil;
import cn.gdut.chengcai.entity.AdminInfo;

/**
 * 后台登录过滤
 */
public class AdminSessionFilter extends OncePerRequestFilter {
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		// 请求的URI
		String uri = request.getRequestURI();

		// uri中包含关键字时才进行过滤
		if (uri.indexOf(getFilterKeyword()) != -1) {
			// 是否过滤
			boolean doFilter = true;
			for (String s : getFilterWhiteList()) {
				if (uri.indexOf(s) != -1) {
					// 如果uri中包含不过滤的uri，则不进行过滤
					doFilter = false;
					break;
				}
			}

			if (doFilter) {// 执行过滤
				AdminInfo admin = (AdminInfo) request.getSession().getAttribute(ConstantUtil.STR_ADMIN);
				if (null == admin) {// 用户未登录，跳转登录页
					String url = RequestUtil.getRequestURLRoot(request) + getLoginURI();
					response.sendRedirect(url);
					return;
				}
			}
		}

		filterChain.doFilter(request, response);
	}

	public String getFilterKeyword() {
		return "/admin/";
	}

	public String[] getFilterWhiteList() {
		return new String[] { "/login", "/loginAction", "/getRandomCode" };
	}

	public String getLoginURI() {
		return "/admin/auth/login.do";
	}

}